package com.swsc.xapp.xroom;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.swsc.xapp.model.DefectAddReqVO;
import com.swsc.xapp.model.DefectEditReqVO;
import com.swsc.xapp.model.RestResp;
import com.swsc.xapp.utils.BeanUtils;
import com.swsc.xapp.utils.ConstantUils;
import com.swsc.xapp.utils.JacksonUtils;
import com.swsc.xapp.utils.NativeJSUtils;
import com.swsc.xapp.utils.ObjectUtils;
import com.swsc.xapp.utils.OfflineChangeUtils;
import com.swsc.xapp.utils.OkHttpUtils;
import com.fasterxml.jackson.core.type.TypeReference;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class OfflineUploadService {
    private static volatile OfflineUploadService instance;

    public static OfflineUploadService getInstance(){
        if (instance == null) {
            synchronized (OfflineUploadService.class) {
                if (instance == null) {
                    instance = new OfflineUploadService();
                }
            }
        }
        return instance;
    }

    private OfflineUploadService(){}

    /**
     * 上传修改数据
     */
    public void uploadChange(){
        JSONObject golbalUrlObj = NativeJSUtils.readCacheGlobalUrl();
        if (null == golbalUrlObj) {
            return;
        }
        JSONObject userInfo = NativeJSUtils.readCacheUserInfo();
        if (null == userInfo) {
            return;
        }
        Long userNo = userInfo.getLong("userNo");
        if (null == userNo) {
            return;
        }
        String apiUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_API_URL);
        String fileUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_FILE_URL);
        String tileUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_TILE_URL);
        String accessToken = userInfo.getString("access_token");

        if (null == apiUrl || null == fileUrl || null == tileUrl || null == accessToken) {
            return;
        }
        List<Integer> changeDefectIn = OfflineChangeUtils.readDefectChange();
        if(null != changeDefectIn && changeDefectIn.size() > 0){
            List<DefectDO> defectDos = DefectService.getInstance().findAllByIds(changeDefectIn);
            if(null != defectDos && defectDos.size() > 0){
                List<Long> defectNoIn = new ArrayList<>();
                List<DefectEditReqVO> editReqVos = new ArrayList<>();
                for(DefectDO defectDo : defectDos){
                    if(null != defectDo.getDefectNo()){
                        defectNoIn.add(defectDo.getDefectNo());
                    }else {
                        defectNoIn.add(Long.valueOf(defectDo.getId()));
                    }
                    DefectEditReqVO reqVo = BeanUtils.copyProperties(defectDo, DefectEditReqVO.class);
                    if(null == defectDo.getDefectNo()){
                        reqVo.setDefectNo(Long.valueOf(defectDo.getId()));
                    }
                    editReqVos.add(reqVo);
                }
                List<InfraredImageDO> infraredImageDos = InfraredImageService.getInstance().listByDefectNoIn(defectNoIn);
                Map<String, List<String>> infraredImgMap = new HashMap<>();
                if(null != infraredImageDos && infraredImageDos.size() > 0){
                    for(InfraredImageDO infraredImageDo : infraredImageDos){
                        Long defectId = null;
                        for(DefectDO defectDo : defectDos){
                            if(null != defectDo.getDefectNo() && Objects.equals(infraredImageDo.getDefectNo(), defectDo.getDefectNo())){
                                defectId = defectDo.getDefectNo();
                                break;
                            }
                        }
                        if(null == defectId){
                            for(DefectDO defectDo : defectDos){
                                Long did = Long.valueOf(defectDo.getId());
                                if(Objects.equals(infraredImageDo.getDefectNo(), did)){
                                    defectId = did;
                                    break;
                                }
                            }
                        }
                        if(null != defectId){
                            OkHttpUtils.builder().addHeader("platform", "android")
                                    .addHeader("Authorization", "Bearer " + accessToken)
                                    .addParam("organNo", infraredImageDo.getOrganNo().toString())
                                    .addParam("defectId", defectId.toString())
                                    .url(apiUrl.concat("/api/v1/m/defect/infrared/image/upload"))
                                    .postForm(infraredImageDo.getFileName(), infraredImageDo.getFileUrl()).async();
                            List<String> imgs = infraredImgMap.get(defectId.toString());
                            if(null == imgs){
                                imgs = new ArrayList<>();
                            }
                            if(!imgs.contains(infraredImageDo.getFileUrl())){
                                imgs.add(infraredImageDo.getFileUrl());
                            }
                            infraredImgMap.put(defectId.toString(), imgs);
                        }
                    }
                }
                if(null != editReqVos && editReqVos.size() > 0){
                    for(DefectEditReqVO reqVo : editReqVos){
                        List<String> infimgs = infraredImgMap.get(reqVo.getDefectNo().toString());
                        if(null != reqVo.getFaultImg() && null != infimgs && infimgs.size() > 0){
                            String infImgStr = "";
                            for(int i = 0; i < infimgs.size(); i++){
                                if(i > 0){
                                    infImgStr = infImgStr + ",";
                                }
                                infImgStr = infImgStr + infimgs.get(i);
                            }
                            if(reqVo.getFaultImg().endsWith(",")){
                                reqVo.setFaultImg(reqVo.getFaultImg() + infImgStr);
                            }else {
                                reqVo.setFaultImg(reqVo.getFaultImg() + ","+infImgStr);
                            }
                        }
                        Map<String, String> paramMap = ObjectUtils.objToMap(reqVo);
                        OkHttpUtils.builder().addHeader("platform", "android")
                                .addHeader("Authorization", "Bearer " + accessToken)
                                .addParam(paramMap)
                                .url(apiUrl.concat("/api/v1/m/defect/edit/").concat(reqVo.getId().toString()))
                                .post(true).async();
                    }
                }
            }

            OfflineChangeUtils.clear(ConstantUils.FILE_OFFLINE_DEFECT_CHANGE);
        }
    }
    /**
     * 上传新曾数据
     */
    public void uploadNew(){
        JSONObject golbalUrlObj = NativeJSUtils.readCacheGlobalUrl();
        if (null == golbalUrlObj) {
            return;
        }
        JSONObject userInfo = NativeJSUtils.readCacheUserInfo();
        if (null == userInfo) {
            return;
        }
        Long userNo = userInfo.getLong("userNo");
        if (null == userNo) {
            return;
        }
        String apiUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_API_URL);
        String fileUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_FILE_URL);
        String tileUrl = golbalUrlObj.getString(ConstantUils.CK_GLOBAL_TILE_URL);
        String accessToken = userInfo.getString("access_token");

        if (null == apiUrl || null == fileUrl || null == tileUrl || null == accessToken) {
            return;
        }
        List<Integer> changeDefectIn = OfflineChangeUtils.readDefectNew();
        if(null != changeDefectIn && changeDefectIn.size() > 0){
            List<DefectDO> defectDos = DefectService.getInstance().findAllByIds(changeDefectIn);
            if(null != defectDos && defectDos.size() > 0){
                List<Long> defectNoIn = new ArrayList<>();
                for(DefectDO defectDo : defectDos){
                    if(null != defectDo.getDefectNo()){
                        defectNoIn.add(defectDo.getDefectNo());
                    }else {
                        defectNoIn.add(Long.valueOf(defectDo.getId()));
                    }
                    DefectAddReqVO reqVo = BeanUtils.copyProperties(defectDo, DefectAddReqVO.class);
                    String faultImgStr = defectDo.getFaultImg();
                    if(!TextUtils.isEmpty(faultImgStr)){
                        String[] faultImgs = faultImgStr.split(",");
                        String newFaultImgStr = null;
                        for(String faultImg : faultImgs){
                            String result = OkHttpUtils.builder().addHeader("platform", "android")
                                    .addHeader("Authorization", "Bearer " + accessToken)
                                    .addParam("organNo", defectDo.getOrganNo().toString())
                                    .url(apiUrl.concat("/api/v1/m/defect/image/upload"))
                                    .postForm(null, faultImg).async();
                            if(null != result){
                                RestResp<List<Map<String, String>>> restResp = JacksonUtils.fromJson2J(result, new TypeReference<RestResp<List<Map<String, String>>>>() {
                                });
                                if(null != restResp && restResp.code == 200 && null != restResp.data && restResp.data.size() > 0){
                                    String imgPath = restResp.data.get(0).get("filePath");
                                    if(null != imgPath && !"".equals(imgPath.trim())){
                                        if(null == newFaultImgStr){
                                            newFaultImgStr = imgPath;
                                        }else {
                                            newFaultImgStr = newFaultImgStr + "," + imgPath;
                                        }
                                    }

                                }
                            }
                        }
                        if(null != newFaultImgStr && !"".equals(newFaultImgStr.trim())){
                            reqVo.setFaultImg(newFaultImgStr);
                        }
                    }
                    reqVo.setId(null);
                    Map<String, String> paramMap = ObjectUtils.objToMap(reqVo);
                    OkHttpUtils.builder().addHeader("platform", "android")
                            .addHeader("Authorization", "Bearer " + accessToken)
                            .addParam(paramMap)
                            .url(apiUrl.concat("/api/v1/m/defect/add"))
                            .post(true).async();

                }
                OfflineChangeUtils.clear(ConstantUils.FILE_OFFLINE_DEFECT_CHANGE);
            }
        }
    }
}
